<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
 
<body>
    <p>【userId】：<div><input id="userId" name="userId" type="text" value="100102"></div></p>
    <p>【toUserId】：<div><input id="toUserId" name="toUserId" type="text" value="100101"></div></p>
    <p>【toUserId】：<div><input id="contentText" name="contentText" type="text" value="你好啊100101"></div></p>
    <p>
    	<div>
    		【操作】：<button onclick="sendMessage()">发送消息</button>
    	</div>
    </p>
	<fieldset>
		<legend>信息展示</legend>
		<div id="message"></div>
	</fieldset>
</body>

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
    var websocket = null;
 
    //判断当前浏览器是否支持WebSocket
    if (typeof(WebSocket) == "undefined") {
    	console.log("您的浏览器不支持WebSocket");  
    } else {
    	// 端口默认为当前tomcat的端口,"cid_0001"就是后端接收的参数cid
        // websocket = new WebSocket("ws://localhost:80/qfxSpringbootWebsocketServerDemo/im/100102");
        websocket = new WebSocket("ws://192.168.1.42:80/websocket/100102");

    	//连接发生错误的回调方法
	    websocket.onerror = function () {
	        setMessageInnerHTML("error");
	    };
	 
	    //连接成功建立的回调方法
	    websocket.onopen = function (event) {
	        setMessageInnerHTML(event.data);
	    }
	 
	    //接收到消息的回调方法
	    websocket.onmessage = function (event) {
	        setMessageInnerHTML(event.data);
	    }
	 
	    //连接关闭的回调方法
	    websocket.onclose = function () {
	        setMessageInnerHTML("close");
	    }
	    
	    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
	    window.onbeforeunload = function () {
	        websocket.close();
	    }
	 
	    //将消息显示在网页上
	    function setMessageInnerHTML(innerHTML) {
	    	if (undefined != innerHTML) {
		        document.getElementById('message').innerHTML += innerHTML + '<br/>';
			}
	    }
	 
	    //关闭连接
	    function closeWebSocket() {
	        websocket.close();
	    }
	 
	    //发送消息
	    function send() {
	        var message = document.getElementById('contentText').value;
	        websocket.send(message);
	    }
	    
	    function sendMessage() {
	        if(typeof(WebSocket) == "undefined") {
	            console.log("您的浏览器不支持WebSocket");
	        }else {
	            console.log("您的浏览器支持WebSocket");
	            console.log('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
	            websocket.send('{"toUserId":"'+$("#toUserId").val()+'","contentText":"'+$("#contentText").val()+'"}');
	        }
	    }
    }
</script>
</html>